//
//  BaseDeomo.m
//  iOSLock
//
//  Created by 崔博 on 2018/7/24.
//  Copyright © 2018年 崔博. All rights reserved.
//

#import "BaseDeomo.h"

@interface BaseDeomo()
@property (assign, nonatomic) int money;
@property (assign, nonatomic) int ticketsCount;

@end

@implementation BaseDeomo
- (instancetype)init
{
    self = [super init];
    if (self)
    {
     
    }
    return self;
}
- (void)moneyTest
{
    self.money = 100;
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            [self __saveMoney];
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i++) {
            [self __drawMoney];
        }
    });
}
- (void)__saveMoney
{
    // 加锁
    int oldMoney = self.money;
    sleep(.2);
    oldMoney += 50;
    self.money = oldMoney;
    
    NSLog(@"还剩余钱%d--%@",oldMoney,[NSThread currentThread]);
    
    // 解锁
}
- (void)__drawMoney
{
    // 加锁
    int oldMoney = self.money;
    sleep(.2);
    oldMoney -= 20;
    self.money = oldMoney;
    
    NSLog(@"还剩余钱%d--%@",oldMoney,[NSThread currentThread]);
    
    // 解锁
}
// 卖票演示
- (void)saleTicket
{
    self.ticketsCount = 15;
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self __saleTickets];
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self __saleTickets];
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 5; i++) {
            [self __saleTickets];
        }
    });
}
- (void)__saleTickets
{
    
    // 加锁
    
    int oldTicketCount = self.ticketsCount;
    sleep(.2);
    oldTicketCount--;
    self.ticketsCount = oldTicketCount;
    
    NSLog(@"还剩票价%d--%@",oldTicketCount,[NSThread currentThread]);
    
    // 解锁
}
@end
